﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using FreeUploadActiveXLib;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Uri url = new Uri("http://kuai.xunlei.com/sendfile");
           // Uri url = new Uri("http://i.xunlei.com/login.html");
            webBrowser1.Url = url;
            //Pupload.Visible = false;
            toolStripStatusLabel1.Text = "正在连接网络...";
            //SHDocVw.WebBrowser wb = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;

            //wb.BeforeNavigate2 +=
            //      new DWebBrowserEvents2_BeforeNavigate2EventHandler(WebBrowser_BeforeNavigate2);
            webBrowser3.Navigate("http://kuai.xunlei.com/sendfile");
            webBrowser1.ScriptErrorsSuppressed = false;
        }

        //private void WebBrowser_BeforeNavigate2(object pDisp, ref object URL, ref object Flags,ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
        //{

        //    string postDataText = System.Text.Encoding.ASCII.GetString(PostData as byte[]);

        //}

        private bool isActiveX()
        {
            
                HtmlElement activex = webBrowser1.Document.GetElementById("upload_size_tips");
                if (activex != null)
                {
                   HtmlElementCollection activexs = activex.GetElementsByTagName("a");
                   if (activexs.Count>0 && activexs[0].InnerText.Contains("安装插件"))
                    {
                        return false;
                    }
                    else
                        return true;
                }
                else
                    return false;
            

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (webBrowser1.IsBusy == false)
            {
                //webBrowser1.Focus();

                if(isActiveX()==false)
                {
                    MessageBox.Show("未安装插件");
                    return ;
                }
                
              
                HtmlElement b = webBrowser1.Document.GetElementById("add_file_container");
                b = webBrowser1.Document.GetElementById("widget_add_localfile_btn");
                b.InvokeMember("click");
                //MessageBox.Show("fdsa");
                HtmlElement isfinsh = webBrowser1.Document.GetElementById("common_tips_layer");
                if (isfinsh != null)
                {
                    HtmlElementCollection div = isfinsh.GetElementsByTagName("div");//t_box所在
                    div = div[1].GetElementsByTagName("div");//tb_wp所在
                    div = div[0].GetElementsByTagName("div");//tb_ts 所在
                    div = div[1].GetElementsByTagName("div");//tb_btn_area
                    div = div[1].GetElementsByTagName("a");//取消所在
                    HtmlElement a = div[1];
                    a.InvokeMember("click");


                }
                freshListView();
            }
            else
                MessageBox.Show("dsa");
        }
        /// <summary>
        /// 刷新列表
        /// </summary>
        private void freshListView()
        {
            Buploadlist.Enabled = false;
            listView1.Items.Clear();
            HtmlElementCollection filescount = webBrowser1.Document.GetElementById("upload_step1_and_2").GetElementsByTagName("ul")[0].GetElementsByTagName("li");
            if (filescount.Count > 1)//列表中有文件
            {
                Buploadlist.Enabled = true;
                for (int i = 1; i < filescount.Count; i++)
                {
                    HtmlElement filename = filescount[i].GetElementsByTagName("p")[0];
                    HtmlElement filesize = filescount[i].GetElementsByTagName("p")[1];
                    ListViewItem li = new ListViewItem();
                    li.SubItems.Add(filename.InnerText);
                    li.SubItems.Add(".rar");
                    li.SubItems.Add(filesize.InnerText);
                    li.SubItems.Add("-");//进度
                    li.SubItems.Add("-");//速度
                    li.SubItems.Add("本地");//类型
                    li.SubItems.Add("等待上传");//状态
                    listView1.Items.Add(li);
                }
            }
        }

        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (webBrowser1.IsBusy == false)
            {
                webBrowser1.Focus();
                HtmlElement b = webBrowser1.Document.GetElementById("add_internet_file_btn");
               b.InvokeMember("click");
                //Moonzwu.VirtualDeivce.VMouse mouse = new VMouse();
                //mouse.Click();
                //
                // webBrowser1.Document.All
            }
            else
                MessageBox.Show("dsa");
        }

        private void button3_Click(object sender, EventArgs e)
        {
         
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (webBrowser1.IsBusy==false&&webBrowser1.Document.Domain=="i.xunlei.com")
            {
                button4.Enabled = false;
                toolStripStatusLabel1.Text = "正在登陆";
                Pupload.Visible = false;
                HtmlElement u = webBrowser1.Document.GetElementById("u");
                u.SetAttribute("value", "iloveyoush@126.com");
                HtmlElement p = webBrowser1.Document.GetElementById("p");
                p.SetAttribute("value", "1102819");
                HtmlElement b = webBrowser1.Document.All["login_btn"];
                
                HtmlElement verifycodeImage = webBrowser1.Document.All["verify_code1"];
                if (verifycodeImage.GetAttribute("src").StartsWith("http://verify2.xunlei.com"))//需要验证码
                {
                    MessageBox.Show(verifycodeImage.GetAttribute("src"));
                }
                //HtmlElement verifycode = webBrowser1.Document.All["verifycode"];
                //    MessageBox.Show(verifycode.GetAttribute("value"));
               
                if (b != null)
                { b.InvokeMember("click");
                setlogininfo = true;
                toolStripStatusLabel1.Text = "登录成功";
                Pupload.Visible = true;
                }
            }
            else
                MessageBox.Show("系统正在准备中，稍后再试！");
        }
        private bool islogin()
        {
            if (webBrowser1.Document.Title.Contains("快传"))
            {
                HtmlElement pageheader = webBrowser1.Document.GetElementById("page_header");
                if (pageheader == null)
                    return false;
                if (pageheader.InnerText.Contains("大坏蛋"))
                {
                    return true;
                }
                else if (pageheader.InnerText.Contains("登陆"))
                { return false; }
                else
                    return false;
            }
            else
                return false;
        }
        bool setlogininfo=false;
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                if (webBrowser1.Document.Domain == "kuai.xunlei.com" && setlogininfo == false)
                {
                    //if (!islogin())//未登录
                    //{
                    HtmlElementCollection urlpanle = webBrowser1.Document.GetElementById("upload_size_tips").GetElementsByTagName("a");
                    if (urlpanle.Count > 0 && urlpanle[0].InnerText == "登录")//有登陆连接
                    {
                        string url = urlpanle[0].GetAttribute("href");
                        webBrowser1.Navigate(url);
                        Pupload.Visible = true;
                        toolStripStatusLabel1.Text = "网络已准备好，请登录。";
                        button4_Click(null,null);
                    }
                    //}
                }
                if (webBrowser1.Document.Domain == "i.xunlei.com" && setlogininfo == false)
                {
                    button4_Click(null, null);
                }

            }
            catch (Exception ex)
            {
 
            }
        }
        
    

      

        #region 同步通过POST方式发送数据
        /// <summary>
        /// 通过POST方式发送数据
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">Post数据</param>
        /// <param name="cookie">Cookie容器</param>
        /// <returns></returns>
        public string SendDataByPost(string Url, string postDataStr, ref CookieContainer cookie)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        #endregion

        public void login()
        {
            HtmlElement verifycode = webBrowser1.Document.All["verifycode"];
            //    MessageBox.Show(verifycode.GetAttribute("value"));
            string yzm = verifycode.GetAttribute("value");
            string url="http://login.xunlei.com/sec2login/";
            string p = GetMD5(GetMD5("1102819"));
            p = GetMD5(p + yzm.ToUpper());
            string post="u=iloveyoush@126.com&p="+p+"&verifycode="+yzm.ToUpper()+"&login_enable=0&login_hour=720";
            CookieContainer cookie=new CookieContainer();
         //  string ret= SendDataByPost(url, post, ref cookie);
           // string ret = PostData(post, url);
            webBrowser1.Navigate(url, "", Encoding.ASCII.GetBytes(post), "Content-Type:application/x-www-form-urlencoded");
           
        }
        public static string PostData(string pInfo,string posturl)
        {
            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("Referer", "http://i.xunlei.com/login.html?redirect_url=http%3A%2F%2Fkuai.xunlei.com%2Fsendfile%3Fcachetime%3D1325661124524");
            byte[] postData = Encoding.ASCII.GetBytes( pInfo);
            byte[] responseData = wc.UploadData(posturl, "POST", postData);
            return Encoding.UTF8.GetString(responseData);
        }
        public static string GetMD5(string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }

            return byte2String;
        }
        int listcount = 0;
        private void Bupload_Click(object sender, EventArgs e)
        {
            Buploadlist.Enabled = false;
            toolStripStatusLabel1.Text = "正在处理...";
            HtmlElement upload = webBrowser1.Document.All["starUploadBtn"];
            HtmlElementCollection files = webBrowser1.Document.GetElementById("upload_step1_and_2").GetElementsByTagName("ul")[0].GetElementsByTagName("li");
            if (files.Count<=1)
            {
                MessageBox.Show("没有要上传的文件");
                return;
            }
            listcount = files.Count - 1;
            upload.InvokeMember("click");
            Blocal.Enabled = false;
            Bweb.Enabled = false;
             Tloadprocess.Enabled = true;
        }
 int complet = 1;
        private void Tloadprocess_Tick(object sender, EventArgs e)
        {
            try
            {
                if (webBrowser1.Document.Domain == "kuai.xunlei.com")
                {

                    HtmlElement progress = webBrowser1.Document.All["progress_list"];

                    HtmlElementCollection lists = progress.GetElementsByTagName("tr");

                    HtmlElementCollection items = lists[complet].GetElementsByTagName("td");//任务列表
                    HtmlElementCollection em = items[2].GetElementsByTagName("em");//每个任务进度
                    if (em.Count > 0)
                    {
                        toolStripStatusLabel1.Text = "当前第" + complet.ToString() + "个文件，共" + listcount.ToString() + "个文件。";
                        //label1.Text = em[0].InnerText;//进度
                        listView1.Items[complet - 1].SubItems[4].Text = em[0].InnerText;
                        HtmlElementCollection span = items[2].GetElementsByTagName("span");
                        //label1.Text += span[1].InnerText;//速度
                        listView1.Items[complet - 1].SubItems[5].Text = span[1].InnerText;
                        listView1.Items[complet - 1].SubItems[7].Text = "上传中...";
                    }
                    if (em.Count == 0)
                    {

                        //label1.Text =items[2].InnerText;//上传完成
                        listView1.Items[complet - 1].SubItems[7].Text = items[2].InnerText;
                        listView1.Items[complet - 1].SubItems[4].Text = "100%";//进度
                        if (complet == listcount)
                        {
                            Tloadprocess.Enabled = false;
                            toolStripStatusLabel1.Text = "列表上传完毕";
                            Blocal.Enabled = true;
                            Bweb.Enabled = true;
                            Buploadlist.Enabled = true;
                            return;
                        }
                        complet = complet + 1;
                    }



                }
                else
                    Tloadprocess.Enabled = false;
            }
            catch (Exception ex)
            {
             
                Tloadprocess.Enabled = false;
                
                Blocal.Enabled = true;
                Bweb.Enabled = true;
                Buploadlist.Enabled = true;
                listView1.Items.Clear();
                MessageBox.Show("当前文件上传出错，请取消该文件上传");
            }
        }

       

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (Tloadprocess.Enabled == true)
            {
              toolStripStatusLabel1.Text= "正在上传中，不能取消。";
                e.Item.Checked = false;
                return;
            }
            if (e.Item.Checked)
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("确定要取消上传该文件吗?", "取消上传", messButton);
                if (dr == DialogResult.OK)//如果点击“确定”按钮
                {

                    string name = e.Item.SubItems[1].Text;
                    string size = e.Item.SubItems[3].Text;
                    HtmlElementCollection filescount = webBrowser1.Document.GetElementById("upload_step1_and_2").GetElementsByTagName("ul")[0].GetElementsByTagName("li");
                    if (filescount.Count > 1)//列表中有文件
                    {
                        for (int j = 1; j < filescount.Count; j++)
                        {
                            HtmlElement filename = filescount[j].GetElementsByTagName("p")[0];
                            HtmlElement filesize = filescount[j].GetElementsByTagName("p")[1];

                            if (filename.InnerText == name && filesize.InnerText == size)
                            {
                                HtmlElement close = filescount[j].GetElementsByTagName("a")[0];
                                close.InvokeMember("click");
                            }
                        }
                    }
                    freshListView();
                }

                else//如果点击“取消”按钮
                {

                    e.Item.Checked = false;

                }
            }

        }

      
        
      
 

        private void button2_Click_1(object sender, EventArgs e)
        {
           
            //回调
            //up.SetFailedCallBack("upload_widget_failed_callback");
            //up.SetProgressCallBack("upload_widget_progress_callback");
          //  up.SetUploadCompleteCallBack("upload_widget_complete_callback");
            //


            UploadClass up = new UploadClass();
            string s1 = webBrowser3.Document.Cookie;

            up.Init(181624321);
            has_resumed_file_res_cache = up.IsContinueFile();
            up.AddFile();
            int total = up.GetFileIndex();
            if (total > 0)
            {
                for (int l = 0; l < total; l++)
                {
                    string info = up.GetFileListByIndex(l);
                }
            }
            object o = up.GetFileList();
            int F = up.GetFileStatusByIndex(0);
            string s = up.GetProgress();
            string i = up.GetFileListByIndex(0);
            string x = up.GetTaskID();
            string v = up.GetVersion();

            up.Upload(0, 0, 0, 0);
            string id = up.GetTaskID();//短连接
            string r = up.GetProgress();
        }
        void upload_widget_complete_callback(int fileindex, bool allCompleted, bool callByHandFlag)
        { }
        int has_resumed_file_res_cache;

        private void BTpost_Click(object sender, EventArgs e)
        {
            
            login();
        }
       


        //int has_resumed_file()//是否有续传任务
        //{
        //    this.has_resumed_file_res_cache = up.IsContinueFile();
        //    return this.has_resumed_file_res_cache;
        //}
        //void init()
        //{
        //    up.Init(181624321);//初始化
        //}
       
    }
}
